<template>
  <div style="height: 100%;">
    <Map ref="map"></Map>
    <div class="bottom" v-if="list.length > 0">
      <div class="kkModule">
        <Module :cfg="moduleCfg[0]">
          <PieChart :data="pieChartData" :cfg="pieChartCfg"></PieChart>
        </Module>
        <div class="kkModule-sub"></div>
      </div>
      <div class="kkModule">
        <Module :cfg="moduleCfg[1]">
          <div class="imgs" ref="mutter">
            <ul :style="{width:getWidth(list.length)}">
              <li v-for="(item,idx) in list" @click="focusEvt(item.gis)" @dblclick="dblClick(item.id)"
                  style="position: relative">
                <img :src="item.source===2?item.imagePath:webCfg.api.url+':'+webCfg.api.fileSvrPort+'/'+item.imagePath"
                     draggable="false">
              </li>
            </ul>
          </div>
          <span class="left arrow" v-show="list.length>0" :class="{disable:scrollLeft<=0}" @click="moveSroll(0)"><i
            class="el-icon-arrow-left"></i></span>
          <span class="right arrow" v-show="list.length>0"
                :class="{disable:list.length<=6 || scrollLeft>=getWidth(list.length-1)}"
                @click="moveSroll(1)"><i class="el-icon-arrow-right"></i></span>

        </Module>
        <div class="kkModule-sub"></div>
      </div>
    </div>

    <div class="timeSeletor" style="position: fixed; right: 20px; top:80px; background-color: #ccc; z-index: 999999">
      <el-date-picker
        @change="selectTimeRange"
        v-model="dataRange"
        type="daterange"
        format="yyyy-MM-dd"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
    </div>

  </div>
</template>

<script>

  import moment from 'moment';
  import getBroser from "js/getBroser";
  import Map from "comp/common/Map";
  import Module from 'comp/common/Module';
  import PieChart from 'kkui/echarts/PieChart3';

  export default {
    name: "MapMode",
    components: {Map, PieChart, Module},
    data() {
      return {
        dataRange: '',
        webCfg: WebCfg,
        dict: this.$kkui.cache.get('dict'),
        timer: null,
        timer2: null,
        isFrist: 1,
        moduleCfg: [
          {
            icon: WebCfg.icons.centerEvtCount,
            title: `今日路情统计`
          },
          {
            icon: WebCfg.icons.liveEvt,
            title: `实时路情`
          },
        ],

        pieChartData: {},
        pieChartCfg: {
          radius: ['55%', '75%'],
          center: ['20%', '50%'],
          bigFontSize: 16,
          smallFontSize: 14,
          legendRight: 30,
          legendFontSize: 12,
          unit: '次'
        },


        liveEvtIndex: null,
        list: [],

        scrollLeft: 0,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        sTime:'',
        eTime:''
      }
    },
    mounted() {
      this.isFrist = 1;
      this.getCount();
      this.getData();
      this.task();

    },
    methods: {
      selectTimeRange() {
        this.timer && clearInterval(this.timer);
        this.timer2 && clearInterval(this.timer2);
        this.liveEvtIndex=null;
        this.$refs.map.emptyMap();

        if(this.dataRange){
          this.list=[];
          this.sTime = this.dataRange?moment(this.dataRange[0]).format('YYYY-MM-DD'):'';
          this.eTime = this.dataRange?moment(this.dataRange[1]).format('YYYY-MM-DD'):'';
          this.getData();
          this.getCount();
        }else{
          this.list=[];
          this.task();
        }

      },
      task() {
        this.timer = setInterval(() => {
          this.getData();
          this.getCount();

        }, WebCfg.api.timer * 1000);
      },
      getCount() {
        this.$server('monitor.today',{
          startTime:this.sTime,
          endTime:this.eTime
        }).then(data => {
          this.pieChartData = data.map(item => {
            return {
              ...item,
              itemStyle: {
                color: WebCfg.eventColor[item.code]
              }
            }
          });
        });
      },
      getData() {

        this.$server('monitor.liveEvt2', {maxId: this.liveEvtIndex,
          startTime:this.sTime,
          endTime:this.eTime

        }).then(data => {
          if (data['newList'] && data['newList'].length > 0) {
            this.liveEvtIndex = data['newList'].length > 0 ? data['newList'][data['newList'].length - 1].id : null;
          }
          const newList = data['newList'];
          if (newList && newList.length > 0) {
            newList.forEach((item, index) => {
              const fn = () => {
                const camera = item['bscCamera'];
                if (camera) {
                  const id = item.id,
                    code = item['eventTypeTwoCode'],
                    color = WebCfg.eventColor[code],
                    gis = [camera['longitude'], camera['latitude']];
                  let name = this.dict['event'][code];
                  name = name.indexOf('-') > -1 ? name.split('-')[1] : name;
                  this.list.unshift({
                    id,
                    name,
                    time: item['detectedTime'],
                    icon: WebCfg['icons'][code],
                    imagePath: item.imgPath,
                    pos: camera['name'],
                    gis,
                    source: item.source
                  });

                  const _cfg = {
                    type: 'event',
                    id,
                    name,
                    color,
                    gis,
                    icon: require(`@/assets/img/common/icon/event_${color}.png`),
                    data: {
                      preData: item,
                      id,
                      type: 'event',
                      videoPath: item.videoPath,
                      imagePath: item.imgPath,
                      event: code,
                      state: item.state,
                      items: [
                        {
                          key: 'type',
                          label: '类型',
                          value: name,
                          color
                        },
                        {
                          key: 'state',
                          label: '状态',
                          value: this.dict['status'][item.state],
                          color
                        },
                        {
                          key: 'road',
                          label: '路段',
                          value: camera['road'],
                          color
                        },
                        {
                          key: 'pos',
                          label: '位置',
                          value: camera['name'],
                          color
                        },
                        {
                          key: 'detectedTime',
                          label: '时间',
                          value: item['detectedTime'],
                          color
                        }
                      ]
                    },

                  };
                  if (code === '002-007-002') {
                    _cfg.data.items.splice(2, 0, {
                      key: 'visiable',
                      label: '能见度',
                      value: item['distance'] + '米',
                      color
                    })
                  }
                  this.$refs.map && this.$refs.map.addMarker(_cfg)
                }
              };

              if (this.isFrist) {
                fn();
              } else {
                this.timer2 = setTimeout(() => {
                  fn();
                }, 1000 * index)
              }
            });
            this.isFrist = 0;
            // this.s();
          }

          // 清空消失的事件
          if (this.isFrist === 0) {
            const cancelList = data['cancelList'];
            if (cancelList && cancelList.length > 0) {
              cancelList.forEach(item => {
                const index = this.list.findIndex(itm => item.id === itm.id);
                if (index > -1) {
                  this.list.splice(index, 1);
                  this.$refs.map.delMarker(item.id);
                }
              });
            }
          }

        })
      },
      focusEvt(gis) {
        this.$refs.map.focusGis(gis);
      },
      dblClick(id) {
        this.$refs.map.showPanel(id);
      },
      getWidth(length) {
        const w = 250 * length;
        return w + 'px'
      },
      s() {
        let c = getBroser();
        let z = '';
        switch (c) {
          case 'Firefox':
            z = 'DOMMouseScroll';
            break;
          default:
            z = 'mousewheel';
            break;
        }
        this.$refs.mutter.addEventListener(z, (event) => {
          let detail = event.wheelDelta || event.detail;
          let moveForwardStep = -1;
          let moveBackStep = 1;
          let step = 0;
          step = detail > 0 ? moveForwardStep * (250 * 6) : moveBackStep * (250 * 6);
          // event.detail*3;
          this.$refs.mutter.scrollLeft = this.$refs.mutter.scrollLeft + step;
        }, false)
      },
      moveSroll(t) {
        console.log(t);
        const $imgs = this.$refs.mutter;
        $imgs.scrollLeft = $imgs.scrollLeft + (t ? 250 * 6 : -250 * 6);
        this.scrollLeft = $imgs.scrollLeft;
      }
    },
    beforeDestroy() {
      this.timer && clearInterval(this.timer);
      this.timer = null;
      this.timer2 && clearTimeout(this.timer2);
      this.timer2 = null;
    },


  }
</script>

<style scoped lang="scss">
  .bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 178px;
    display: flex;
    gap: 10px;
    background-color: rgba(9, 44, 73, .8);
    z-index: 10;

    .kkModule:first-child {
      width: 300px;
    }

    .kkModule:last-child {
      /deep/ .content {
        overflow: hidden;
        padding: 0;
      }

      .imgs {
        width: calc(250px * 6);
        height: 150px;
        overflow-x: scroll;
        overflow-y: hidden;
        position: relative;
      }

      .btn {
        position: absolute;
        height: 132px;
        width: 30px;
        background-color: rgba(255, 255, 255, .5);
        bottom: 5px;
        z-index: 20;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .btn.left {
        left: 0;
      }

      .btn.right {
        right: 0
      }


    }

    ul {
      position: absolute;
      top: 0;
      left: 0;
      height: 140px;

      li {
        width: 250px;
        height: 140px;
        float: left;
        cursor: pointer;
        padding: 0 1px;
        box-sizing: border-box;

        img {
          height: 100%;
          width: 100%;
        }
      }
    }
  }

  .arrow {
    position: absolute;
    top: calc(50% - 20px);
    color: #fff;
    font-size: 40px;
    cursor: pointer;
  }

  .arrow.disable {
    opacity: .5;
    cursor: not-allowed;
  }

  .arrow.left {
    left: 5px;
  }

  .arrow.right {
    right: 155px;
  }

  .page {
    position: absolute;
    top: -20px;
    right: 155px;
  }

  ::-webkit-scrollbar-thumb {
    -webkit-box-shadow: inset 0 0 0 white;
    background-color: var(--font-green-color);
    border-radius: 1px;
  }
</style>
